<template>
  <ArtTableFullScreen>
    <div class="account-page" id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar v-model:filter="formFilters" :items="formItems" @reset="handleReset" @search="handleSearch">
      </ArtSearchBar>

      <ElCard shadow="never" class="art-table-card">
        <!-- 表格头部 -->
        <ArtTableHeader :columnList="columnOptions" v-model:columns="columnChecks" @refresh="handleRefresh">
          <template #left>
            <!-- <ElButton @click="showDialog('add')">新增用户</ElButton> -->
          </template>
        </ArtTableHeader>

        <!-- 表格 -->
        <ArtTable ref="tableRef" row-key="id" :loading="loading" :data="tableData" :currentPage="pagination.currentPage"
          :pageSize="pagination.pageSize" :total="pagination.total" :marginTop="10"
          @selection-change="handleSelectionChange" @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
          <template #default>
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
          </template>
        </ArtTable>

        <ElDialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加用户' : '编辑用户'" width="30%" align-center>
          <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <ElFormItem label="用户名" prop="username">
              <ElInput v-model="formData.username" />
            </ElFormItem>
            <ElFormItem label="手机号" prop="phone">
              <ElInput v-model="formData.phone" />
            </ElFormItem>
            <ElFormItem label="性别" prop="gender">
              <ElSelect v-model="formData.gender">
                <ElOption label="男" value="男" />
                <ElOption label="女" value="女" />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="角色" prop="role">
              <ElSelect v-model="formData.role" multiple>
                <ElOption v-for="role in roleList" :key="role.roleCode" :value="role.roleCode" :label="role.roleName" />
              </ElSelect>
            </ElFormItem>
          </ElForm>
          <template #footer>
            <div class="dialog-footer">
              <ElButton @click="dialogVisible = false">取消</ElButton>
              <ElButton type="primary" @click="handleSubmit">提交</ElButton>
            </div>
          </template>
        </ElDialog>
      </ElCard>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
import { h } from 'vue'
import { ROLE_LIST_DATA, ACCOUNT_TABLE_DATA } from '@/mock/temp/formData'
import { SearchChangeParams, SearchFormItem } from '@/types/search-form'
import { ElDialog, FormInstance, ElTag, ElSwitch } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import { useCheckedColumns } from '@/composables/useCheckedColumns'
import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
import { UserService } from '@/api/usersApi'
import { ApiStatus } from '@/utils/http/status'


onMounted(() => {
  getUserList()
  getLevelid()
})


const dialogType = ref('add')
const dialogVisible = ref(false)
const loading = ref(false)

// 定义表单搜索初始值
const initialSearchState = {
  id: '',
  level: '',
  mobile: '',
  page: 1,
  limit: 10,
  type: '',
}

const userLevelList = ref([])

// 监听页面数据的变化
watch(userLevelList, (newList) => {
  const levelItem = formItems.find(item => item.prop === 'level')
  if (levelItem) {
    levelItem.options = newList
  }
})
//获取用户等级
const getLevelid = async () => {
  loading.value = true
  try {
    const res = await UserService.getUserLevel()
    if (res.code === ApiStatus.success) {
      loading.value = false
      res.data.forEach((val) => {
        val.label = val.name
        val.value = val.level_id
      });
      userLevelList.value = res.data
    }
  } catch (error) {
    console.error('获取用户等级失败:', error)
    loading.value = false
  }
}



const roleList = ref<any[]>([])

// 响应式表单数据
const formFilters = reactive({ ...initialSearchState })

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])

// 表格实例引用
const tableRef = ref()

// 选中的行数据
const selectedRows = ref<any[]>([])

// 重置表单
const handleReset = () => {
  Object.assign(formFilters, { ...initialSearchState })
  pagination.currentPage = 1 // 重置到第一页
  getUserList()
}

// 搜索处理
const handleSearch = () => {
  console.log('搜索参数:', formFilters)
  pagination.currentPage = 1 // 搜索时重置到第一页
  getUserList()
}

// 表单项变更处理
const handleFormChange = (params: SearchChangeParams): void => {
  console.log('表单项变更:', params)
}

// 表单配置项
const formItems: SearchFormItem[] = [
  // {
  //   label: '用户名',
  //   prop: 'nickname',
  //   type: 'input',
  //   config: {
  //     clearable: true
  //   },
  //   onChange: handleFormChange
  // },
  {
    label: '用户ID',
    prop: 'id',
    type: 'input',
    
    config: {
      clearable: true
    },
    onChange: handleFormChange
  },

  {
    label: '手机号',
    prop: 'mobile',
    type: 'input',
    config: {
      clearable: true
    },
    onChange: handleFormChange
  },
   {
    label: '类型',
    prop: 'type',
    type: 'select',
    options: [
      { label: '普通用户', value: '1' },
      { label: '主播', value: '2' },
      { label: '推广员', value: '3' }
    ],
    onChange: handleFormChange
  },
  {
    label: '用户等级',
    prop: 'level',
    type: 'select',
    config: {
      clearable: true
    },
    options: userLevelList.value,
    onChange: handleFormChange
  },
  // {
  //   label: '地址',
  //   prop: 'address',
  //   type: 'input',
  //   config: {
  //     clearable: true
  //   },
  //   onChange: handleFormChange
  // },
  // {
  //   label: '邮箱',
  //   prop: 'email',
  //   type: 'input',
  //   config: {
  //     clearable: true
  //   },
  //   onChange: handleFormChange
  // },
  // 支持 9 种日期类型定义
  // 具体可参考 src/components/core/forms/art-search-bar/widget/art-search-date/README.md
  // {
  //   prop: 'date',
  //   label: '日期',
  //   type: 'date',
  //   config: {
  //     type: 'date',
  //     placeholder: '请选择日期'
  //   }
  // },
  // {
  //   prop: 'daterange',
  //   label: '日期范围',
  //   type: 'daterange',
  //   config: {
  //     type: 'daterange',
  //     startPlaceholder: '开始时间',
  //     endPlaceholder: '结束时间'
  //   }
  // },
  // {
  //   label: '状态',
  //   prop: 'status',
  //   type: 'radio',
  //   options: [
  //     { label: '在线', value: '1' },
  //     { label: '离线', value: '2' }
  //   ],
  //   onChange: handleFormChange
  // }
]

// 列配置
const columnOptions = [
  // { label: '勾选', type: 'selection' },
  { label: '用户名', prop: 'nickname' },
  { label: 'ID', prop: 'id' },
  { label: '手机号', prop: 'mobile' },
  { label: '类型', prop: 'type' },
  { label: '用户等级', prop: 'level_id' },
  { label: '总流水', prop: 'total_pay' },
  { label: '总充值', prop: 'total_recharge' },
  { label: '金币', prop: 'balance' },
  { label: '钻石', prop: 'point' },
  { label: '成长值', prop: 'grow_value' },
  { label: '直推', prop: 'direct_reat' },
  { label: '间推', prop: 'indirect_reat' },
  { label: '新用户', prop: 'is_new' },
  { label: '禁玩', prop: 'is_all_see' },
  { label: '状态', prop: 'status' },
  { label: '注册时间', prop: 'created_at' },
  { label: '操作', prop: 'operation' }
]

// 获取标签类型
// 1: 在线 2: 离线 3: 异常 4: 注销
const getTagType = (status: string) => {
  console.log(status)
}

// 构建标签文本
const buildTagText = (status: string) => {
  let text = ''
  if (status === '1') {
    text = '在线'
  } else if (status === '2') {
    text = '离线'
  } else if (status === '3') {
    text = '异常'
  } else if (status === '4') {
    text = '注销'
  }
  return text
}

// 显示对话框
const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type

  // 重置表单验证状态
  if (formRef.value) {
    formRef.value.resetFields()
  }

  if (type === 'edit' && row) {
    formData.username = row.username
    formData.phone = row.userPhone
    formData.gender = row.gender === 1 ? '男' : '女'

    // 将用户角色代码数组直接赋值给formData.role
    formData.role = Array.isArray(row.userRoles) ? row.userRoles : []
  } else {
    formData.username = ''
    formData.phone = ''
    formData.gender = '男'
    formData.role = []
  }
}

// 删除用户
const deleteUser = () => {
  ElMessageBox.confirm('确定要注销该用户吗？', '注销用户', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    ElMessage.success('注销成功')
  })
}

// 动态列配置
const { columnChecks, columns } = useCheckedColumns(() => [
  // { type: 'selection' }, // 勾选列
  {
    fixed: 'left',
    prop: 'avatar',
    label: '用户名',
    width: 120,
    formatter: (row: any) => {
      return h('div', { class: 'user', style: 'display: flex; align-items: center' }, [
        h('img', { class: 'avatar', src: row.avatar }),
        h('div', {}, [
          h('p', { class: 'user-name' }, row.nickname),
          h('p', { class: 'email' }, row.id)
        ])
      ])
    }
  },
  { prop: 'real_name', label: '姓名' },
  
  {
    prop: 'is_anchor',
    label: '总流水',
    formatter: (row: any) => {
      return (row.is_anchor == 1?'主播':row.is_agent == 1?'推广员':'普通用户')
    }
  },
  {  width: 120,prop: 'mobile', label: '手机号' },
  
  { width: 120, prop: 'level_id', label: '用户等级' },
  {
    prop: 'total_pay',
    label: '总流水', width: 120,
    formatter: (row: any) => {
      return row.account.total_pay
    }
  },
  {
    prop: 'total_recharge',
    label: '总充值', width: 120,
    formatter: (row: any) => {
      return row.account.total_recharge
    }
  },
  {
    prop: 'balance',
    label: '金币', width: 120,
    formatter: (row: any) => {
      return row.account.balance
    }
  },
  {
    prop: 'point',
    label: '钻石', width: 120,
    formatter: (row: any) => {
      return row.account.point
    }
  },
  {
    prop: 'grow_value',
    label: '成长值', width: 120,
    formatter: (row: any) => {
      return row.account.grow_value
    }
  },
  {
    prop: 'direct_reat',
    label: '直推', width: 120,
    formatter: (row: any) => {
      return row.direct_reat + '%'
    }
  },
  {
    prop: 'indirect_reat',
    label: '间推', width: 120,
    formatter: (row: any) => {
      return row.indirect_reat + '%'
    }
  },
  {
    prop: 'is_new',
    label: '新用户',
    formatter: (row) => {
      return h(ElSwitch, {
        modelValue: row.is_new === 1 ? true : false,
        'onUpdate:modelValue': (val) => {
          row.is_new = val ? 1 : -1 // 更新status值为1(启用)或-1(禁用)
          newUserhandleStatusChange(row)
        },
        inlinePrompt: true,
        activeText: '显示',
        inactiveText: '隐藏',
      })
    }
  },
  {
    prop: 'is_all_see',
    label: '禁玩',
    formatter: (row) => {
      return h(ElSwitch, {
        modelValue: row.is_all_see === 1 ? true : false,
        'onUpdate:modelValue': (val) => {
          row.is_all_see = val ? 1 : -1 // 更新status值为1(启用)或-1(禁用)
          playerhandleStatusChange(row)
        },
        inlinePrompt: true,
        activeText: '是',
        inactiveText: '否',
      })
    }
  },
  {
    prop: 'status',
    label: '状态',
    formatter: (row) => {
      return h(ElSwitch, {
        modelValue: row.status === 1 ? true : false,
        'onUpdate:modelValue': (val) => {
          row.status = val ? 1 : -1 // 更新status值为1(启用)或-1(禁用)
          handleStatusChange(row)
        },
        inlinePrompt: true,
        activeText: '启用',
        inactiveText: '禁用',
      })
    }
  },
  {
    prop: 'created_at',
    width: 200,
    label: '创建时间',
    sortable: true
  },
  {
    prop: 'operation',
    label: '操作',
    width: 200,
    fixed: 'right', // 固定在右侧
    formatter: (row: any) => {
      return h('div', [
        h(ArtButtonTable, {
          type: 'edit',
          text: '详情',
          onClick: () => showDialog('edit', row)
        }),
        h(ArtButtonTable, {
          type: 'delete',
          text: '充值',
          onClick: () => deleteUser()
        })
      ])
    }
  }
])
// 是否注销账户
const handleStatusChange = (row) => {
  console.log(`ID:${row.id} 的状态已更新为: ${row.status == 1 ? '正常' : '已注销'}`)
  putuserStatus(row)
}
// 是否禁玩
const playerhandleStatusChange = (row) => {
  console.log(`ID:${row.id} 的状态已更新为: ${row.status == 1 ? '是' : '否'}`)
  putStatusPlay(row)
}
// 是否是新用户 是的话隐藏所有盒子否则显示
const newUserhandleStatusChange = (row) => {
  console.log(`ID:${row.id} 的状态已更新为: ${row.status == 1 ? '显示' : '隐藏'}`)
  getUserSta(row)
}

// 是否新用户
const getUserSta = async (row) => {
  loading.value = true
  try {
    const params = {
      status:row.status
    }
    const res = await UserService.getUserupdateUsersStatus(row.id,params)
    if (res.code === ApiStatus.success) {
      ElMessage.success(res.msg)
      loading.value = false
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    loading.value = false
  }
}
// 是否禁玩
const putStatusPlay = async (row) => {
  loading.value = true
  try {
    const params = {
      status:row.status
    }
    const res = await UserService.getUserupdateUserStatus(row.id,params)
    if (res.code === ApiStatus.success) {
      ElMessage.success(res.msg)
      loading.value = false
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    loading.value = false
  }
}
// 是否注销
const putuserStatus = async (row) => {
  loading.value = true
  try {
    const params = {
      status:row.status
    }
    const res = await UserService.getUserStatus(row.id,params)
    if (res.code === ApiStatus.success) {
      ElMessage.success(res.msg)
      loading.value = false
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    loading.value = false
  }
}
// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  username: '',
  phone: '',
  gender: '',
  role: [] as string[]
})


// 获取用户信息

const getUserList = async () => {
  loading.value = true
  try {
    const params = {
      ...formFilters,
      page: pagination.currentPage,
      limit: pagination.pageSize,
    }
    const res = await UserService.getUserList(params)
    if (res.code === ApiStatus.success) {
      console.log(res)
      const records = res.data.data
      tableData.value = records
      loading.value = false
      pagination.currentPage
      pagination.pageSize = res.data.per_page
      pagination.total = res.data.total
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    loading.value = false
  }
}

const getRoleList = () => {
  roleList.value = ROLE_LIST_DATA
}

const handleRefresh = () => {
  getUserList()
}

// 处理表格行选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 表单验证规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
    }
  })
}

// 处理表格分页变化
const handleSizeChange = (newPageSize: number) => {
  pagination.pageSize = newPageSize
  getUserList()
}

const handleCurrentChange = (newCurrentPage: number) => {
  pagination.currentPage = newCurrentPage
  getUserList()
}
</script>

<style lang="scss" scoped>
.account-page {
  :deep(.user) {
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }

    >div {
      margin-left: 10px;

      .user-name {
        font-weight: 500;
        color: var(--art-text-gray-800);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
